/* eslint-disable no-return-await */
/* eslint-disable import/prefer-default-export */
const request = require('request');
const downLoadGit = require('download-git-repo');
const { getAll } = require('./rc');
const { DOWNLOAD } = require('../constants');

const fetch = async (url) => new Promise((resolve, reject) => {
  const config = {
    url,
    method: 'get',
    headers: {
      'user-agent': 'xxx',
    },
  };
  request(config, (err, response, body) => {
    if (err) {
      reject(err);
    }
    console.log(body, 'body');
    resolve(JSON.parse(body));
  });
});

// 链接地址：https://api.github.com/repos/zhufeng-cli/vue-template/tags 版本
const tagList = async (repo) => {
  const config = await getAll();
  const api = `https://api.github.com/repos/${config.registry}/${repo}/tags`;
  return await fetch(api);
};

// 链接地址：https://api.github.com/orgs/zhufeng-cli/repos 项目

const repoList = async () => {
  const config = await getAll();
  const api = `https://api.github.com/${config.type}/${config.registry}/repos`;
  return await fetch(api);
};

const download = async (src, dest) => new Promise((resolve, reject) => {
  downLoadGit(src, dest, (err) => {
    if (err) {
      reject(err);
    }
    resolve();
  });
});

// 下载到本地
const downloadLocal = async (project, version) => {
  const config = await getAll();
  let api = `${config.registry}/${project}`;
  if (version) {
    api += `#${version}`;
  }
  return await download(api, `${DOWNLOAD}/${project}`);
};
module.exports = {
  tagList,
  repoList,
  downloadLocal,
};
